package com.atguigu.srb.core.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
@Slf4j
@Configuration
public class RabbitMqConfig {
    //配置生产者回调
    @Resource
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        //配置生产者确认回调
        //是否到达交换机的回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause)->{
            if(!ack){
                log.error("消息没有达到交换机: correlationData-> {},ack-> {},cause-> {}"
                        , JSON.toJSONString(correlationData) , ack,cause);
            }

        });
        //没有到达队列的回调
        rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange, String routingKey)->{
            log.error("消息没有到达队列: replyCode-> {},replyText->{},exchange-> {},routingKey->{},message-> {}",
                    replyCode,replyText,exchange,routingKey,new String(message.getBody()));
        });
    }

    @Bean
    public Exchange srbExchange(){
        return ExchangeBuilder.topicExchange("exchange.srb")
                .durable(true) //交换机持久化
                .ignoreDeclarationExceptions()
                .build();
    }
//    //创建交换机
//    @Bean
//    public Exchange test1Exchange(){
//        return ExchangeBuilder.topicExchange("exchange.test1")
//                    .durable(true) //交换机持久化
//                    .ignoreDeclarationExceptions()
//                    .build();
//    }
//    //创建队列
//    @Bean
//    public Queue test1Queue(){
//        return QueueBuilder.durable("queue.test1")
//                    .build();
//    }
//    //创建队列和交换机的绑定对象
//    @Bean
//    public Binding test1Binding(Exchange test1Exchange, Queue test1Queue){
//        return BindingBuilder.bind(test1Queue)
//                    .to(test1Exchange)
//                    .with("a.#")
//                    .noargs();
//
//    }
}
